package com.only4play.mybatis.support;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.google.common.base.Preconditions;
import com.only4play.common.validator.CreateGroup;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * 实体创建器
 *
 * @author liyuncong
 * @date 2023/11/07 09:43
 **/
@Slf4j
public class EntityCreator<T> extends BaseEntityOperation implements CreateHandler<T>, UpdateHandler<T>, Executor<T> {

    private final BaseMapper<T> baseMapper;
    private T entity;
    private Consumer<T> successHook = t -> log.info("save success");
    private Consumer<? super Throwable> failureHook = Throwable::printStackTrace;

    public EntityCreator(BaseMapper<T> baseMapper) {
        this.baseMapper = baseMapper;
    }

    @Override
    public UpdateHandler<T> create(Supplier<T> supplier) {
        this.entity = supplier.get();
        return this;
    }

    @Override
    public Executor<T> update(Consumer<T> consumer) {
        Preconditions.checkArgument(Objects.nonNull(entity), "entity must supply");
        consumer.accept(this.entity);
        return this;
    }

    @Override
    public Optional<T> execute() {
        doValidate(this.entity, CreateGroup.class);
        baseMapper.insert(entity);
        return Optional.ofNullable(this.entity);
    }

    @Override
    public Executor<T> successHook(Consumer<T> consumer) {
        this.successHook = consumer;
        return this;
    }

    @Override
    public Executor<T> failureHook(Consumer<? super Throwable> consumer) {
        this.failureHook = consumer;
        return this;
    }
}
